package tyris.socket;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Date;

import org.apache.log4j.Logger;

import tyris.common.Constants;
import tyris.control.ScanControl;
import tyris.util.DateUtil;

/**
 * TCP Client : Receive image data Socket : 30586
 * 
 * @author WXJ
 *
 *         2018年9月19日
 */
public class FullDuplexClient {

	private static Logger logger = Logger.getLogger(FullDuplexClient.class);

	private static InputStream inStr = null;
	private static OutputStream outStr = null;
	private static Thread tRecv = new Thread(new RecvThread());
	public static Socket socket = null;
	private static int r;
	private static File file = null;

	public FullDuplexClient(String ip) {
		try {
//			socket = new Socket(ip, Constants.TCP_IMG);
//			socket.setSoTimeout(1000);
			socket = new Socket();
			socket.connect(new InetSocketAddress(ip, Constants.TCP_IMG), 1000);
			if (tRecv.isAlive() == false) {
				tRecv.start();
			}
			outStr = socket.getOutputStream();
			inStr = socket.getInputStream();
		} catch (Exception e) {
			logger.error("Receive Image Data Socket Exception!  " + DateUtil.format(new Date()));
			logger.error(e);
			socket = null;
			outStr= null;
			inStr = null;
		}
	}

	/**
	 * Receive Image Data
	 */
	private static class RecvThread implements Runnable {
		public void run() {
			try {
				while (true) {
					if (null != inStr && inStr.available() != 0) {
						String binName = Constants.CONF_PATH + ScanControl.binName;
						file = new File(binName);
						FileOutputStream fos = new FileOutputStream(file, true);
						int a = inStr.available();
						byte[] b = new byte[a];
						r = inStr.read(b);
						if (r > -1) {
							fos.write(b);
							fos.close();
						}
					}
					if (file == null || !file.exists()) {
						Thread.sleep(500);
					}
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				logger.error("FullDuplexClient Exception!" + DateUtil.format(new Date()));
				logger.error(e);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				logger.error("FullDuplexClient Exception!" + DateUtil.format(new Date()));
				logger.error(e);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				logger.error("FullDuplexClient Exception!" + DateUtil.format(new Date()));
				logger.error(e);
			}

		}
	}

	/**
	 * send byte
	 * 
	 * @param b
	 */
	public static void sendMSG(byte[] b) {
		try {
			outStr.write(b);
		} catch (Exception e) {
			logger.error("Send Message Exception!  " + DateUtil.format(new Date()));
			logger.error(e);
		}
	}

}
